
var guiguVue = new Vue({
	el:'#homePage',
	data(){


		return {
			openId:'',

			//提交资料
			contactName:'',
			contactPhone:'',
			courseName:'',
			contactNameError: false,
			contactPhoneError: false,
			courseNameError: false,
			showDialog: false,
			course: [
				'英语零基础',
				'英语1年学习基础',
				'英语2年及以上学习基础',
				//'英语3年及以上学习基础'
			],
			referrer: '', // 推荐码


			// 分享拼团页面
			// courseItems: [
			// 	{ 'name': 'Wonders--启蒙班', id: 10001 ,'info': '启蒙班：适合英语零基础的孩子'},
			// 	{ 'name': 'Wonders--基础班', id: 10002 ,'info': '基础班：适合已有一年左右英语学习基础的孩子'},
			// 	{ 'name': 'Wonders--进阶班', id: 10003 ,'info': '进阶班：适合已有两年及以上英语学习基础的孩子'},
			// ],
			courseItems: [
				{ 'name': 'Wonders--启蒙班', id: 10001 ,'info': '适合英语零基础的孩子'},
				{ 'name': 'Wonders--基础班', id: 10002 ,'info': '适合已有一年左右英语学习基础的孩子'},
				{ 'name': 'Wonders--进阶班', id: 10003 ,'info': '适合已有两年及以上英语学习基础的孩子'},
			],
			courseData:{},
			courses:[],
			groupInfo:{
				groupMaxNumber: 0
			},
			groupEndTime: '',
			groupEndDate: '', // 截止时间
			isEnd:false,
			isJoin:false,
			countdown: 0,
			showShareTip: false,
			priceInfo:[0,14400,4800,1600,960,640,0], //省钱的钱数，索引对应人数
			//groupPriceTip:['一学期64<br>课时为例','2人班<br>14400元/人<br>(225元/课时)','3人班<br>9600元/人<br>(150元/课时)','4人班<br>8000元/人<br>(125元/课时)'],// group省的钱数及文案，索引对应人
			groupPriceTip:['一学期64<br>课时为例','2人班<br>250元/课时','3人班<br>175元/课时','4人班<br>145元/课时'],// group省的钱数及文案，索引对应人
			gpFixBtn: false, // 分享页吸底按钮
			groupOrderId_d:'',

			//首页
			banner:{
				list:[
					{ 'src': 'images/home/index_2.jpg', title: '面对面线下场景互动教学，高沉浸，高成效' },
					{ 'src': 'images/home/index_3.jpg', title: '情景式口语对话，让孩子自然输出，流利表达' },
					{ 'src': 'images/home/index_4.jpg', title: '思辨性阅读模式，激发孩子思维逻辑养成' }
				]
			},
			teacher:{
				list: [
					{ name: 'Sarah', info: 'Sarah毕业于伦敦大学亚非学院中文系。她对少儿教育经验丰富，对教学严谨认真，热情满满。尤其擅长用肢体语言和变化丰富的表情使课堂氛围生动饱满，更能灵活的运用游戏寓教于乐，让学生轻松的提升口语及各项能力。', src: 'images/home/teacher2.jpg', },
					{ name: 'Conor', info: 'Conor来自于美国洛杉矶，毕业于美国著名私立文理学院科尔盖特大学，并在清华大学主攻中文。Conor热情、幽默、亲和力强，总能让羞涩的孩子开口。他同时也擅长用对话手法潜移默化的培养孩子的逻辑思维。Conor在中国工作和教学超过五年。', src: 'images/home/teacher1.jpg', },
					{ name: 'Gladys', info: 'Gladys毕业于美国加州大学伯克利分校，双修心理与经济系，对儿童心理学研究颇深。Gladys高中就读英国国际学校，拥有自己的一套方法论来提高英语的学习效率和效果：学习初期重视发音，大量跟读模仿；平时大量输入感兴趣的原版题材；根据艾宾浩斯曲线来积累词汇，温故知新…在实践中，她对中西方思维和语言学习建立了自己的独特见解。', src: 'images/home/teacher3.jpg', },
					{ name: 'Olivia', info: 'Olivia 英文专业科班出身，曾任英国领事馆文化教育处高级官员多年，负责英国文化教育相关项目。后迁居美国斯坦福大学，在斯坦福教育学院研习儿童教育课程。Olivia是二宝妈妈，曾在家辅导自家孩子，使其英语能力接近欧美同龄孩子水平。', src: 'images/home/teacher4.jpg', }
				],
			},

			//发起拼团的首页
			showGuize:false,

			isOriginator:false, //是否发起人

			isSubmitBtnClicked: false // 提交按钮是否已点击


		}
	},
	methods:{
		getUrlData(dataName){
			function getUrlVars(){ 
        var vars = {}, hash; 
        var href = window.location.href.split('#')[0];
        var hashes = href.slice(href.indexOf('?')+1).split('&'); 
        for(var i = 0; i < hashes.length; i++) { 
            hash = hashes[i].split('=');
            vars[hash[0]] = hash[1]?hash[1]:'';
        } 
        return vars; 
			} 
			var params = getUrlVars(); 
			
			for(var key in params){
					if(key == dataName){ 
							return params[key];
					}
			};
			return '';
		},
		submitData(){
			// 阻止首页报名多次误提交
			if (this.isSubmitBtnClicked) {
				return;
			}
			this.isSubmitBtnClicked = true; // 将按钮状态改为已点击

			var self = this;
			var putData = {
				"courseName": this.courseName,
				"contactName": this.contactName,
				"contactPhone": this.contactPhone
			};
			var source = '';
			if(this.referrer){
				putData.source = "Referral: " + this.referrer;
			} else {
				source = this.getUrlData('channel');
				if(source){
					putData.source = decodeURIComponent(source);
				}
			}

			guigu.showLoading({
				title: '数据加载中',
				mask: true
			});

			$.ajax({
				url: 'https://api.svenglish.cn/api/order/course/enroll',
				type: 'PUT',
				contentType: 'application/json',
				data: JSON.stringify(putData),
				success: function(data){
					if (data.code==1) {

						localStorage.setItem('contactInfo',JSON.stringify(putData))
						
						if(self.isWeiXin() && !localStorage.getItem('wxUserInfo')){
							location.href = 'login.html?url=https://www.svenglish.cn/success.html';
						}else{
							// 处理缓存没有unionId的问题
							var wxUserInfo = localStorage.getItem('wxUserInfo');
							if( wxUserInfo ) {
									wxUserInfo = JSON.parse(wxUserInfo);
									if(!wxUserInfo.unionId && self.isWeiXin()) {
									location.href = 'login.html?url=https://www.svenglish.cn/success.html';
									return;
								} 
							}							
							location.href = 'success.html';
						}

						self.courseName = '';
						self.contactName = '';
						self.contactPhone = '';
						// self.showDialog = true;

						
						
					}else{
						//关闭loading
						guigu.hideLoading();
						guigu.showModal({
							content: '提交失败，请重试！',
							showCancel: false
						});
						this.isSubmitBtnClicked = false; // 将按钮状态改为可点击

					}
				}
			});	
		},
    submitFn(){

			if(!this.contactName){
				this.contactNameError = true;
				return;
			}else if(!/^1\d{10}$/.test(this.contactPhone)){
				this.contactPhoneError = true;
				this.contactNameError = false;
				return;
			}else if(!this.courseName){
				this.courseNameError = true;
				this.contactPhoneError = false;
				return;
			}else{
				this.courseNameError = false;
				this.submitData();
			}
		},

		/**前置倒零 */
		leadingZero(num){
			return	num < 10 ? '0' + num : num;
		},
		timeRun(){
			if(this.countdown<=0){ return;}			
			/**
			 * 处理截止时间
			 */
			var end = new Date(new Date().getTime() + this.countdown),
					y = end.getFullYear(),
					M = this.leadingZero(end.getMonth() + 1),
					d = this.leadingZero(end.getDate()),
					h = this.leadingZero(end.getHours()),
					m = this.leadingZero(end.getMinutes());

			this.groupEndDate  = y + '-' + M + '-' + d + ' ' + h + ':' + m;		
		},
		getUser(userIds){
			var self = this;

			$.ajax({
				url: 'https://api.svenglish.cn/api/wechat/user-info?userId=' + userIds.join(','),
				type: 'GET',
				success:function(data){
					if (data.code == 1) {
						var userInfo = data.data;
						var courses = JSON.parse(JSON.stringify(self.courses));
						for (var i = 0; i < courses.length; i++) {
							if(userInfo[i] && userInfo[i].avatarUrl){
								courses[i].userName = userInfo[i].userName;
								courses[i].avatarUrl = userInfo[i].avatarUrl;
							}
							
						};
						self.courses = courses;
						
					}
				}
			});	

		},
		//获取列表
		getCourses(groupOrderId){
			var self=this;

			$.ajax({
				url: 'https://api.svenglish.cn/api/order/courses',
				type: 'POST',
				contentType: 'application/json',
				data: JSON.stringify({
					groupOrderId: groupOrderId //'148644921'
				}),
				success:function(data){
					if (data.code==1){
						var courses = data.data;
						self.courses = courses;
	
						for (var i = 0; i < courses.length; i++) {
							if (self.openId && self.openId == courses[i].openId && self.isWeiXin()) {
								self.isJoin = true;
							}
						};

	
						if (!self.isEnd){
							//开始倒计时
							self.timeRun();
						}
	
						var openIdArr = [];
						for (var i = 0; i < courses.length;i++){
							openIdArr.push(courses[i].openId);
						}
						

						//获取用户头像
						self.getUser(openIdArr);
						
	
					}
				}
			});	
		},
		getGroup(groupOrderId){
			if (!groupOrderId){
				return;
			}
			var self = this;

			$.ajax({
				url: 'https://api.svenglish.cn/api/order/groups',
				type: 'POST',
				contentType: 'application/json',
				data: JSON.stringify({
					groupOrderId: groupOrderId //'148644921'
				}),
				success:function(data){
					if (data.code == 1) {
						var data = data.data;
						self.groupInfo = data[0];


						self.isEnd = self.groupInfo.status=='GROUP_PROGRESS' ? false : true;
						//获取入团人员
						self.getCourses(groupOrderId);

						self.courseData = self.getCourseData(self.groupInfo.courseId);
						
						//调取分享
						if(/group/.test(location.href) && self.isWeiXin()){
							var urlPath = window.location.href.split('?')[0].replace(/(.+\/).*$/g, '$1'); //URL根目录
							guigu.share({
								title: '我发起了一个少儿英语免费试听课--外教上门，小班拼课', // 分享标题
								desc: self.courseData.info+'，邀请你和我一起参加!', // 分享描述
								link: location.origin + location.pathname +location.search, //分享地址
								imgUrl: urlPath+'images/logo_square.png',  //分享的图片地址，需绝对路径
								success: function () { 
									
								},
								cancel: function () { 
									
								}
							});
						}
						
					}
				}
			});	

		},
		getCountdown(groupOrderId){
			var self = this;

			$.ajax({
				url: 'https://api.svenglish.cn/api/order/group/countdown?groupOrderId=' + groupOrderId, // 仅为示例，并非真实的接口地址
				type: 'GET',
				success:function(data){
					if (data.code == 1) {
						//获取入团人员
						self.getGroup(groupOrderId);
						self.countdown = data.data<=0 ? 0 : data.data;
					}
				}
			});	
			
		},
		isWeiXin(){
			var ua = window.navigator.userAgent.toLowerCase();
			if(ua.match(/MicroMessenger/i) == 'micromessenger'){
				return true;
			}else{
				return false;
			}
		},
		addGroup() {
    
			// var dataset = e.currentTarget.dataset;
			// 判断是否已经拼团
			var courses = this.courses;
			for (var i = 0; i < courses.length;i++){
				if (this.openId && this.openId == courses[i].openId && this.isWeiXin()) {
					guigu.showModal({
						content: '您已经参加过了，请查看我的拼团！',
						showCancel: false
					});
					return false;
				}
			};

			// 拼团页面判断是否是从附近拼班过来的 就带上stranger参数
			var stranger = this.getUrlData('stranger'),
					nearby = stranger ? '&stranger=1' : '';

			if(this.isWeiXin() && !localStorage.getItem('wxUserInfo')){
				location.href = 'login.html?url='+encodeURIComponent('https://www.svenglish.cn/order.html?groupOrderId='+this.groupInfo.groupOrderId+'&courseId=' + this.groupInfo.courseId);
			}else{
				location.href = 'order.html?groupOrderId=' + this.groupInfo.groupOrderId +'&courseId=' + this.groupInfo.courseId + nearby;
			}
			
			
			//location.href = 'myOrder.html?groupOrderId=' + this.groupInfo.groupOrderId
		},
		getCourseData(courseId){
			var courseItems = this.courseItems;
			for(var i=0;i<courseItems.length;i++){
				var thisData = courseItems[i];
				if(thisData.id == courseId){
					return thisData;
				}
			}
		},
		getValue(id,key){
			var courseItems = this.courseItems;
			for (var i = 0; i < courseItems.length;i++){
				if (courseItems[i].id == id){
					return courseItems[i][key];
				}
			}
		},
		shareFn(type){
			this.showShareTip = true;

			var self= this;
			if(type=='gather' && /group/.test(location.href) && self.isWeiXin()){
				var urlPath = window.location.href.split('?')[0].replace(/(.+\/).*$/g, '$1'); //URL根目录
				var fxInfo = {
					title: '我向你推荐一个少儿英语免费试听课--外教上门，小班拼课。', // 分享标题
					desc: '针对3～12岁孩子，基于美国小学课程标准，与中国小学无缝对接!', // 分享描述
					//link: location.origin + '/' + type+'.html', //分享地址
					link: location.origin + '/index.html',
					imgUrl: location.origin + '/images/logo_square.png',
					//imgUrl: urlPath+'images/logo_square.png',  //分享的图片地址，需绝对路径
					success: function () { 
						
					},
					cancel: function () { 
						
					}
				}
				wx.onMenuShareTimeline(fxInfo);
				wx.onMenuShareAppMessage(fxInfo);
				// guigu.share();
			}
			this.shareFnCount();
		},
		// 分享统计
		shareFnCount(){
			if (!this.groupOrderId_d) {
				return;
			}
			$.ajax({
				url: 'https://api.svenglish.cn/api/order/share-record?groupOrderId=' + this.groupOrderId_d, // 仅为示例，并非真实的接口地址
				type: 'POST',
				contentType: 'application/json',
				success:function(data){
				}
			});
		},
		

		goOrder(){
			if(this.isWeiXin() && !localStorage.getItem('wxUserInfo')){
				location.href = 'login.html?url=https://www.svenglish.cn/order.html';
			}else{
				location.href = 'order.html';
			}
			
		},

		// 分享页吸底
		handleScroll() {
			let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
			let offsetTop = this.$refs.sBtn.offsetTop;
			this.gpFixBtn = scrollTop > (offsetTop + this.$refs.sBtn.offsetHeight);
		},

		// group页浏览事件
		countShareReanFn(){
			let self = this;
			if(self.isJoin || !this.groupOrderId_d) {
				return;
			}
			$.ajax({
				url: 'https://api.svenglish.cn/api/order/visited-record?groupOrderId=' + this.groupOrderId_d, // 仅为示例，并非真实的接口地址
				type: 'POST',
				contentType: 'application/json',
				success:function(data){
				}
			});
		}

  },
  watch:{
    
  },
	mounted() {

		//获取团
		if(/group/.test(location.href)){
			var groupOrderId = this.getUrlData('groupOrderId');
			var wxUserInfo = localStorage.getItem('wxUserInfo');
			if(wxUserInfo){
				var wxUserInfo = JSON.parse(wxUserInfo);
				this.openId = wxUserInfo.unionId;
			};

			if(groupOrderId){
				this.getCountdown(groupOrderId);
				this.groupOrderId_d = groupOrderId;

				// 如果是团页面，则添加监听滚动
				window.addEventListener('scroll', this.handleScroll);

				// 如果是拼团页面，并且是通过分享过来的，统计一次浏览事件
				/groupmessage/.test(location.href) && setTimeout(() => {this.countShareReanFn()},1800);
				
				// 拼团页先取用户信息，取不到则登录
				if (!this.openId && this.isWeiXin()) {
					location.href = 'login.html?url='+encodeURIComponent(location.href.split('#')[0]);
				}
			}			
			

			var createGroupOrderIds = localStorage.getItem('createGroupOrderIds');
			if(createGroupOrderIds && createGroupOrderIds.indexOf(groupOrderId)){
				this.isJoin = true;
			}
			
		}


		
		

		var tabIndex = this.getUrlData('tabIndex');
		if(tabIndex){
			this.courseName = this.course[tabIndex];
		}
		
		
		this.$nextTick(function(){
			
			new Swiper('#js_swiper1', {
				autoplay: false,//可选选项，自动滑动
				slidesPerView :"auto",
			});

			new Swiper('#js_swiper2', {
				autoplay: false,//可选选项，自动滑动
				slidesPerView :"auto",
				pagination : '.swiper-pagination',
			});
			

		});

		// 获取推荐码
		var referrer =  this.getUrlData('referrer');
		if (referrer) {
			this.referrer = decodeURIComponent(referrer);
		}

	}
});



